from machine import Pin, PWM
import time

"""
ES08A 180度舵机
改变角度
0.5ms 0°
1.5ms 90°
2.5ms 180°
需要5V电压
"""


class Servo:
    def __init__(self, pin_num):
        self.freq = 50
        self.pwm = PWM(Pin(pin_num), freq=self.freq, duty=0)

    def write_angle(self, angle=0):
        """
        angle 0-180
        """
        if angle > 180:
            angle = angle % 180
        if angle < 0:
            angle = 0
        d = angle / 90 + 0.5
        # print(d)
        duty = int(d / 20 * 1023)
        self.pwm.duty(duty)

    def stop(self):
        self.pwm.deinit()


if __name__ == "__main__":
    servo = Servo(0)
    servo.write_angle(0)
    time.sleep(1)
    servo.write_angle(45)
    time.sleep(1)
    servo.write_angle(90)
    time.sleep(1)
    servo.write_angle(135)
    time.sleep(1)
    servo.write_angle(180)
    time.sleep(1)
    servo.stop()
